package ua.soso.ui.dwr;

import org.directwebremoting.WebContext;
import org.directwebremoting.WebContextFactory;
import org.directwebremoting.annotations.RemoteMethod;
import org.directwebremoting.annotations.RemoteProxy;
import org.directwebremoting.extend.OutputStreamLoaderInputStreamFactory;
import org.directwebremoting.io.FileTransfer;
import org.directwebremoting.io.InputStreamFactory;
import org.directwebremoting.io.OutputStreamLoader;
import org.springframework.beans.factory.annotation.Required;
import ua.soso.service.FileService;
import ua.soso.service.bean.FileBean;
import ua.soso.service.bean.UserBean;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

/**
 * Created by Babka Aleksey
 * Date: 03.05.12
 */
@RemoteProxy(name = "FileServiceRemote")
public class FileServiceRemote {
    private FileService fileService;

    @Required
    public void setFileService(FileService fileService) {
        this.fileService = fileService;
    }

    @RemoteMethod
    public boolean uploadFile(String description, long categoryId, String path, boolean isPublic, InputStream fileStream) {
        try {
            String fileName = path.substring(path.lastIndexOf(File.separator) + 1, path.length());

            WebContext ctx = WebContextFactory.get();
            HttpSession session = ctx.getSession();

            long userId = ((UserBean) session.getAttribute("logged")).getId();

            fileService.saveFile(description, categoryId, userId, fileName, isPublic, fileStream);
        } catch (Exception e) {
            return false;
        }

        return true;
    }

    @RemoteMethod
    public FileTransfer getFile(final String fileId, String fileName) {
        InputStreamFactory factory = new OutputStreamLoaderInputStreamFactory(new OutputStreamLoader() {
            @Override
            public void load(OutputStream outputStream) throws IOException {
                fileService.getFile(fileId, outputStream);
            }

            @Override
            public void close() throws IOException {
            }
        });

        return new FileTransfer(fileName, "application/zip", factory);
    }

    @RemoteMethod
    public List<FileBean> getUserFiles() {
        WebContext ctx = WebContextFactory.get();
        HttpSession session = ctx.getSession();

        long userId = ((UserBean) session.getAttribute("logged")).getId();

        return fileService.getUserFiles(userId);
    }

    @RemoteMethod
    public List<FileBean> getAllFiles() {
        WebContext ctx = WebContextFactory.get();
        HttpSession session = ctx.getSession();

        long userId = ((UserBean) session.getAttribute("logged")).getId();

        return fileService.getAllFiles(userId);
    }
}
